<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Message extends Controller {

	public function action_index()
	{
	}

	public function action_list()
	{
		$message_list = ORM::factory('message');
		if ($_GET)
		{
			$category_id = arr::get($_GET, 'category_id');
			$page = arr::get($_GET, 'page');
			$num_in_page = arr::get($_GET, 'num_in_page');
			$order = arr::get($_GET, 'order');

			if ($category_id != NULL)
			{
				$message_list->where('category_id', '=', $category_id);
			}
			if ($order != NULL)
			{
				switch ($order)
				{
				case 0:
					$message_list->order_by('create_time', 'ASC');
					break;
				case 1:
					$message_list->order_by('create_time', 'DESC');
					break;
				case 2:
					$message_list->order_by('popular', 'DESC');
					break;
				default:
					break;
				}
			}
		}
		
		$query_result = $message_list->find_all();
		if (isset($page) AND isset($num_in_page))
		{
			$result = $this->create_message_list(array_slice($query_result->as_array(), ($page - 1) * $num_in_page, $num_in_page));
		}
		else
		{
			$result = $this->create_message_list($query_result->as_array());
		}
		echo json_encode($result);
	}

	protected function create_message_list($array)
	{
		$object = array();
		foreach ( $array as $message)
		{
			array_push($object,
				array(
					'id'				=> $message->id,
					'category_id'		=> $message->category_id,
					'content'			=> $message->content,
					'popular'			=> $message->popular,
					'create_time'   	=> $message->create_time,
				));
		}
		return array(
			'count' => count($object),
			'data'  => $object
		);
	}

} // End Message
